package Java.view.game.doudizhurule;

import Java.utils.JDBC;
import Java.view.Common.teamFX;
import domain.Poker;
import domain.User;
import domain.User1;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.embed.swing.JFXPanel;
import javafx.scene.control.TextField;
import javafx.stage.Stage;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import java.net.Socket;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.*;


public class doudizhuJFrame extends JFrame implements ActionListener {
    public  int w = 830;
    public  int h = 620;

    public int diZhuFlag;
    public int turn;

    int f=0;
    boolean flag1=false;
    int flag=0;
    ArrayList<Poker> zancun = new ArrayList<>();

    ArrayList<Poker> player00 = new ArrayList<>();
    ArrayList<Poker> player11 = new ArrayList<>();
    ArrayList<Poker> player22 = new ArrayList<>();
    public JTextField wait = new JTextField("等待思考中...");
    public JButton fen10 = new JButton("不叫");
    public JButton fen11 = new JButton("1分");
    public JButton fen12 = new JButton("2分");
    public JButton fen13 = new JButton("3分");
    public JButton toReturn=new JButton();

    public int i = 1;
    private ArrayList<String> lord = new ArrayList<>();
    User user1 = new User(null);
    User user2 = new User(null);
    User user3 = new User(null);
    int dizhuID;
    public static Socket socket;

    static {
        try {
            socket = new Socket("127.0.0.1", 8848);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    private static BufferedWriter writer;
    private static BufferedReader reader;
    public Container container = null;

    //管理抢地主和不抢两个按钮
    public JButton[] landlord = new JButton[2];
    public JButton[] dizhufenshu = new JButton[4];
User user;
    //管理出牌和不要两个按钮
    public JButton[] publishCard = new JButton[2];
    JButton yao=new JButton();
    JButton NoYao=new JButton();
    public String[] players = new String[3];

    //游戏界面中地主的图标
    public JLabel diZhu;
    public User1 player = new User1();

    //集合嵌套集合
    //大集合中有三个小集合
    //小集合中装着每一个玩家当前要出的牌
    //0索引：左边的电脑玩家
    //1索引：中间的自己
    //2索引：右边的电脑玩家
    public ArrayList<ArrayList<Poker>> currentList = new ArrayList<>();

    //集合嵌套集合
    //大集合中有三个小集合
    //小集合中装着每一个玩家的牌
    //0索引：左边的电脑玩家
    //1索引：中间的自己
    //2索引：右边的电脑玩家
    public ArrayList<ArrayList<Poker>> playerList = new ArrayList<>();
    //底牌
    public ArrayList<Poker> lordList = new ArrayList<>();

    //牌盒，装所有的牌
    ArrayList<Poker> pokerList = new ArrayList<>();
    ArrayList<Poker> poker11 = new ArrayList<>();
    ArrayList<Poker> poker00 = new ArrayList<>();
    ArrayList<Poker> poker22 = new ArrayList<>();


    //三个玩家前方的文本提示
    //0索引：左边的电脑玩家
    //1索引：中间的自己
    //2索引：右边的电脑玩家
    public JTextField[] time = new JTextField[3];

    //用户操作，涉及多线程的知识
    PlayerOperation po;
    PlayerOperation1 po1;
    public boolean nextPlayer = false;

    public doudizhuJFrame(User user, int i) throws IOException, SQLException {
        this.user=user;
        user.setHappyDou(user.getHappyDou()-100);
//更新数据库信息
        Connection connection= JDBC.getConnection();
        Statement statement=connection.createStatement();
        String sql = "UPDATE user SET happyDou = '" + user.getHappyDou()+ "' WHERE username = '" + user.getUsername() + "'";
        statement.executeUpdate(sql);

        if (i == 1) {
            //设置图标
            setIconImage(Toolkit.getDefaultToolkit().getImage("src/image/dizhu.png"));
            //设置界面
            initJFrame();
            //添加组件
            initView();
            //界面显示出来
            //先展示界面再发牌，因为发牌里面有动画，界面不展示出来，动画无法展示
            this.setVisible(true);
            //初始化牌
            //准备牌，洗牌，发牌
            new Thread(this::initCard).start();

            //打牌之前的准备工作
            //展示抢地主和不抢地主两个按钮并且再创建三个集合用来装三个玩家准备要出的牌
            initGame();
        } else if (i == 2) {
            //设置图标
            setIconImage(Toolkit.getDefaultToolkit().getImage("src/image/dizhu.png"));
            //设置界面
            initZuJFrame();

            //连接服务器
            String message = "login1#" + user.getUsername() + "#" + user.getPassword() + "$";
            socket = new Socket("127.0.0.1", 8848);

            writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
            reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));

            try {
                writer.write(message);
                writer.newLine();
                writer.flush();

            } catch (IOException e) {
                System.out.println("客户发送登录信息时出现异常");
                throw new RuntimeException(e);
            }
            BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            String usernames = in.readLine();
            System.out.println(usernames);
            BufferedReader in1 = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            String usernamess = in1.readLine();
            System.out.println(usernamess);
            players = usernames.split("#");
            if (usernamess.endsWith("$")) {
                usernamess = usernamess.substring(0, usernamess.length() - 1);
            }
            for (int j = 0; j < 3; j++) {
                if (Objects.equals(players[j], user.getUsername())) {
                    switch (j) {
                        case 0:
                            user1.setUsername(players[0]);
                            user2.setUsername(players[1]);
                            user3.setUsername(players[2]);
                            break;
                        case 1:
                            user1.setUsername(players[1]);
                            user2.setUsername(players[2]);
                            user3.setUsername(players[0]);
                            break;
                        case 2:
                            user1.setUsername(players[2]);
                            user2.setUsername(players[0]);
                            user3.setUsername(players[1]);
                            break;
                    }
                    break;
                }
            }
            String loadCard = in1.readLine();
            System.out.println(loadCard);
            if (loadCard.endsWith("$")) {
                loadCard = loadCard.substring(1, loadCard.length() - 1);
            }

            JLabel player1 = new JLabel(user1.getUsername());
            Font forget = new Font(null, Font.ITALIC, 16);
            player1.setForeground(Color.yellow);
            player1.setFont(forget);
            player1.setBounds(400, 410, 100, 20);
            this.getContentPane().add(player1);

            JLabel player2 = new JLabel(user2.getUsername());
            player2.setForeground(Color.yellow);
            player2.setFont(forget);
            player2.setBounds(150, 210, 100, 20);
            this.getContentPane().add(player2);

            JLabel player3 = new JLabel(user3.getUsername());
            player3.setForeground(Color.yellow);
            player3.setFont(forget);
            player3.setBounds(650, 210, 100, 20);
            this.getContentPane().add(player3);

            ArrayList<String> datalist = new ArrayList<>();
            String[] splitArray = usernamess.split("#");
            Collections.addAll(datalist, splitArray);
            player.playerID = Integer.parseInt(datalist.get(1));
            player.receiveCardsFromServer(datalist.get(2));
            String[] splitArrayy = loadCard.split("#");
            String[] splitArray1 = splitArrayy[1].split(" ");
            Collections.addAll(lord, splitArray1);

//            initView1();
            this.setVisible(true);
            animateShuffling();

            lookPoker("玩家"+player.playerID, player.handCards);

            System.out.println("我的id" + player.playerID);
            Thread qiangdizhuThread = new Thread(() -> {
                try {
                    qiangdizhu();
                } catch (InterruptedException | IOException e) {
                    e.printStackTrace();
                }
            });
            qiangdizhuThread.start();
        }


    }



    public void lookPoker(String name, ArrayList<String> list) {
        System.out.print(name + ": ");
        for (String poker : list) {
            System.out.print(poker + " ");
        }
        System.out.println();
    }


    private void initZuJFrame() {
        //设置标题
        this.setTitle("房间");
        //设置大小
        this.setSize(830, 620);
        //设置关闭模式
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        //设置窗口无法进行调节
        this.setResizable(false);
        //界面居中
        this.setLocationRelativeTo(null);
        //获取界面中的隐藏容器，以后直接用无需再次调用方法获取了
        container = this.getContentPane();
        //取消内部默认的居中放置
        container.setLayout(null);
        //设置背景颜色
        container.setBackground(new Color(34, 139, 34));
    }

    //初始化牌
    //准备牌，洗牌，发牌
    public void initCard() {
        //准备牌
        //把所有的牌，包括大小王都添加到牌盒cardList当中
        for (int i = 1; i <= 5; i++) {
            for (int j = 1; j <= 13; j++) {
                if ((i == 5) && (j > 2)) {
                    break;
                } else {
                    Poker poker = new Poker(this, i + "-" + j, false);
                    poker.setLocation(350, 150);
                    pokerList.add(poker);
                    container.add(poker);
//                    container.setComponentZOrder(poker, 0);
                }
            }
        }

        //洗牌
        Collections.shuffle(pokerList);

        //创建三个集合用来装三个玩家的牌，并把三个小集合放到大集合中方便管理
        ArrayList<Poker> player0 = new ArrayList<>();
        ArrayList<Poker> player1 = new ArrayList<>();
        ArrayList<Poker> player2 = new ArrayList<>();

        for (int i = 0; i < pokerList.size(); i++) {
            //获取当前遍历的牌
            Poker poker = pokerList.get(i);

            //发三张底牌
            if (i <= 2) {
                //移动牌
                Common.move(poker, poker.getLocation(), new Point(270 + (75 * i), 10));
                //把底牌添加到集合中
                lordList.add(poker);
                container.setComponentZOrder(poker, 0);
                continue;
            }
            //给三个玩家发牌
            if (i % 3 == 0) {
                //给左边的电脑发牌
                Common.move(poker, poker.getLocation(), new Point(50, 60 + i * 5));
                player0.add(poker);
            } else if (i % 3 == 1) {
                //给中间的自己发牌
                Common.move(poker, poker.getLocation(), new Point(180 + i * 7, 450));
                player1.add(poker);
                //把自己的牌展示正面
                poker.turnFront();

            } else {
                //给右边的电脑发牌
                Common.move(poker, poker.getLocation(), new Point(700, 60 + i * 5));
                player2.add(poker);
            }
            //把三个装着牌的小集合放到大集合中方便管理
            playerList.add(player0);
            playerList.add(player1);
            playerList.add(player2);

            //把当前的牌至于最顶端，这样就会有牌依次错开且叠起来的效果
            container.setComponentZOrder(poker, 0);
        }
        //给牌排序
        for (int i = 0; i < 3; i++) {
            //排序
            Common.order(playerList.get(i));
            //重新摆放顺序
            Common.rePosition(this, playerList.get(i), i);
        }
    }

    //打牌之前的准备工作
    private void initGame() {
        //创建三个集合用来装三个玩家准备要出的牌
        for (int i = 0; i < 3; i++) {
            ArrayList<Poker> list = new ArrayList<>();
            //添加到大集合中方便管理
            currentList.add(list);
        }

        //展示抢地主和不抢地主两个按钮
        landlord[0].setVisible(true);
        landlord[1].setVisible(true);

        //展示自己前面的倒计时文本
        time[1].setVisible(true);
        //倒计时30秒
        po = new PlayerOperation(this, 30,user);
        //开启倒计时
        po.start();
    }
    public void panduandizhu() throws IOException {
        if (flag == 1) {
            System.out.println("抢地主结束");
            try (Socket socket = new Socket("127.0.0.1", 8848)) {
                socket.setSoTimeout(5000); // 设置超时为5秒

                try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
                     BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()))) {

                    // 发送完成抢地主的请求
                    writer.write("calllandlordfinished");
                    writer.newLine();
                    writer.flush();

                } catch (IOException e) {
                    System.out.println("客户发送请求或读取响应时出现异常");
                    e.printStackTrace();
                }
            } catch (IOException e) {
                System.out.println("连接服务器时出现异常");
                e.printStackTrace();
            }
        }
    }
    @Override
    public void actionPerformed(ActionEvent e) {
        if (e.getSource() == toReturn) {
            JFXPanel fxPanel = new JFXPanel(); // 这个JFXPanel不需要添加到Swing组件中，只需要它来初始化JavaFX
            Platform.runLater(() -> {
                try {
                    new teamFX().start(new Stage()); // 启动JavaFX窗口
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            });

        // 显示Swing窗口
        }


        if(e.getSource()==yao){
//遍历手上的牌，把要出的牌都放到临时集合中
            flag1=false;
            ArrayList<Poker> c = new ArrayList<>();
            for (Poker poker : player11) {
                if (poker.isClicked()) {
                    c.add(poker);
                    player.pokeGroup.add(fanpanduan(poker.getName()));
                }

            }
            player.pokeGroup.isLegal();
            System.out.println(player.pokeGroup.getpokegroup());
            if(!(player.pokeGroup.type.equals("不出"))) {
                if (player.pokeGroup.compareTo(player.LastpokeGroup) > 0 || (player.LastpokeGroup.type.equals("不出") && player.LastLastpokeGroup.type.equals("不出"))
                        || (player.LastpokeGroup.type.equals("不出") && player.pokeGroup.compareTo(player.LastLastpokeGroup) > 0)) {
                    if (player.number == player.pokeGroup.pokegroup.size()) {
                        System.out.println("victory#" + player.playerID + "#" +player.isLandlord+  "#" + player.pokeGroup.getpokegroup() + "#" + player.pokeGroup.getCountNumber() + "$");
                        player.sendDataToServer("victory#" + player.playerID + "#" +player.isLandlord+ "#" + player.pokeGroup.getpokegroup() + "#" + player.pokeGroup.getCountNumber() + "$");
                        System.out.println("玩家" + player.playerID + "victory");
                        if(player.playerID==dizhuID){
                            user.setExp(user.getExp()+5);
                            user.setHappyDou(user.getHappyDou()+300);
                            Connection connection= JDBC.getConnection();
                            Statement statement= null;
                            try {
                                statement = connection.createStatement();
                            } catch (SQLException ex) {
                                throw new RuntimeException(ex);
                            }
                            String sql1 = "UPDATE user SET exp = '" + user.getExp()+ "' WHERE username = '" + user.getUsername() + "'";
                            String sql2 = "UPDATE user SET happyDou = '" + user.getHappyDou()+ "' WHERE username = '" + user.getUsername() + "'";
                            try {
                                statement.executeUpdate(sql1);
                                statement.executeUpdate(sql2);
                            } catch (SQLException ex) {
                                throw new RuntimeException(ex);
                            }
                            showJDialog("地主胜利，恭喜您赢了!(欢乐豆+300)");
                        }else{
                            user.setExp(user.getExp()+5);
                            user.setHappyDou(user.getHappyDou()+200);
                            Connection connection= JDBC.getConnection();
                            Statement statement= null;
                            try {
                                statement = connection.createStatement();
                            } catch (SQLException ex) {
                                throw new RuntimeException(ex);
                            }
                            String sql = "UPDATE user SET exp = '" + user.getExp()+ "' WHERE username = '" + user.getUsername() + "'";
                            try {
                                statement.executeUpdate(sql);
                            } catch (SQLException ex) {
                                throw new RuntimeException(ex);
                            }
                            showJDialog("农民胜利，恭喜您赢了(欢乐豆+200)");
                        }
                    }
                    else {
                        if((player.LastpokeGroup.type.equals("不出") && player.LastLastpokeGroup.type.equals("不出"))){
                            for(Poker poker:poker00){
                                container.remove(poker);
                            }
                            for(Poker poker:poker22){
                                container.remove(poker);
                            }
                        }

                        player.sendDataToServer("playcard#" + player.playerID + "#" + player.pokeGroup.getpokegroup() + "#" + player.pokeGroup.getCountNumber() + "$");
                        System.out.println("已发送playcard#" + player.playerID + "#" + player.pokeGroup.getpokegroup() + "#" + player.pokeGroup.getCountNumber() + "$");

                        //计算坐标并移动牌
                        //移动的目的是要出的牌移动到上方
                        poker11.addAll(c);
                        Point point = new Point();
                        point.x = (770 / 2) - (c.size() + 1) * 15 / 2;
                        point.y = 300;
                        for (Poker poker : c) {
                            player.number--;
                            zancun.add(poker);
                            Common.move(poker, poker.getLocation(), point);
                            point.x += 15;
                            player11.remove(poker);
                        }
                        Common.rePosition(this, player11, 1);
                        player.pokeGroup.removeAll();
                        buttonHidden();
                    }
                }else{
                    player.pokeGroup.removeAll();
                }
            }else{
                player.pokeGroup.removeAll();
            }

        }

        if(e.getSource()==NoYao){
            f=1;
            flag1=false;
            if(player.LastpokeGroup.type.equals("不出")){
                for(Poker poker:poker22){
                    container.remove(poker);
                }
            }
            if(player.LastpokeGroup.type.equals("不出")&&player.LastLastpokeGroup.type.equals("不出")){
                System.out.println("不可不出，请出牌");

            }
            else{
                player.sendDataToServer("playcard#"+player.playerID+"#不出# #0$");
                System.out.println("已发送playcard#"+player.playerID+"#不出# #0$");
                buttonHidden();
            }
        }
        if (e.getSource() == dizhufenshu[0]) {
            player.clickedZeroScore();
            po1.isRun = false;
            time[0].setText("不叫");
            for (int i = 0; i < 4; i++) {
                container.remove(dizhufenshu[i]);
            }
            container.repaint();

            if(player.playerID==3){
                flag++;
            }
            try {
                panduandizhu();
            } catch (IOException ex) {
                System.out.println("判断出毛病了");
                throw new RuntimeException(ex);
            }
        }
        if (e.getSource() == dizhufenshu[1]) {
            player.clickedOneScore();
            po1.isRun = false;
            time[0].setText("1分");
            for (int i = 0; i < 4; i++) {
                container.remove(dizhufenshu[i]);
            }
            container.repaint();
            if(player.playerID==3){
                flag++;
            }
            try {
                panduandizhu();
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
        }
        if (e.getSource() == dizhufenshu[2]) {
            player.clickedTwoScore();
            po1.isRun = false;
            time[0].setText("2分");
            for (int i = 0; i < 4; i++) {
                container.remove(dizhufenshu[i]);
            }
            container.repaint();
            if(player.playerID==3){
                flag++;
            }
            try {
                panduandizhu();
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
        }
        if (e.getSource() == dizhufenshu[3]) {

            player.clickedThreeScore();
            po1.isRun = false;
            time[0].setText("3分");
            for (int i = 0; i < 4; i++) {
                container.remove(dizhufenshu[i]);
            }
            container.repaint();
            if(player.playerID==3){
                flag++;
            }
            try {
                panduandizhu();
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
        }

        if (e.getSource() == landlord[0]) {
            //点击抢地主
            time[1].setText("抢地主");
            po.isRun = false;
        } else if (e.getSource() == landlord[1]) {
            //点击不抢
            time[1].setText("不抢");
            po.isRun = false;
        } else if (e.getSource() == publishCard[1]) {
            //点击不要
            this.nextPlayer = true;
            currentList.get(1).clear();
            time[1].setText("不要");
        } else if (e.getSource() == publishCard[0]) {
            //点击出牌

            //创建一个临时的集合，用来存放当前要出的牌
            ArrayList<Poker> c = new ArrayList<>();
            //获取中自己手上所有的牌
            ArrayList<Poker> player2 = playerList.get(1);

            //遍历手上的牌，把要出的牌都放到临时集合中
            for (Poker poker : player2) {
                if (poker.isClicked()) {
                    c.add(poker);
                }
            }

            int flag = 0;
            //判断，如果左右两个电脑玩家是否都不要
            if (time[0].getText().equals("不要") && time[2].getText().equals("不要")) {
                if (Common.judgeType(c) != PokerType.c0) {
                    flag = 1;
                }
            } else {
                flag = Common.checkCards(c, currentList, this);
            }

            if (flag == 1) {
                //把当前要出的牌，放到大集合中统一管理
                currentList.set(1, c);
                //在手上的牌中，去掉已经出掉的牌
                player2.removeAll(c);

                //计算坐标并移动牌
                //移动的目的是要出的牌移动到上方
                Point point = new Point();
                point.x = (770 / 2) - (c.size() + 1) * 15 / 2;
                point.y = 300;
                for (Poker poker : c) {
                    Common.move(poker, poker.getLocation(), point);
                    point.x += 15;
                }

                //重新摆放剩余的牌
                Common.rePosition(this, player2, 1);
                //赢藏文本提示
                time[1].setVisible(false);
                //下一个玩家可玩
                this.nextPlayer = true;
            }
        }
    }

    //添加组件
    public void initView() {
        //返回的按钮
        toReturn.setBounds(15,8,50,50);
        toReturn.setOpaque(false);
        toReturn.setContentAreaFilled(false);
        toReturn.setBorderPainted(false);
        toReturn.setIcon(new ImageIcon("src/image/返回.png"));
        toReturn.setFocusPainted(false);
        toReturn.addActionListener(this);
        this.getContentPane().add(toReturn);

        //创建抢地主的按钮
        JButton robBut = new JButton("抢地主");
        //设置位置
        robBut.setBounds(320, 400, 75, 20);
        //添加点击事件
        robBut.addActionListener(this);
        //设置隐藏
        robBut.setVisible(false);
        //添加到数组中统一管理
        landlord[0] = robBut;
        //添加到界面中
        container.add(robBut);

        //创建不抢的按钮
        JButton noBut = new JButton("不     抢");
        //设置位置
        noBut.setBounds(420, 400, 75, 20);
        //添加点击事件
        noBut.addActionListener(this);
        //设置隐藏
        noBut.setVisible(false);
        //添加到数组中统一管理
        landlord[1] = noBut;
        //添加到界面中
        container.add(noBut);

        //创建出牌的按钮
        JButton outCardBut = new JButton("出牌");
        outCardBut.setBounds(320, 400, 60, 20);
        outCardBut.addActionListener(this);
        outCardBut.setVisible(false);
        publishCard[0] = outCardBut;
        container.add(outCardBut);

        //创建不要的按钮
        JButton noCardBut = new JButton("不要");
        noCardBut.setBounds(420, 400, 60, 20);
        noCardBut.addActionListener(this);
        noCardBut.setVisible(false);
        publishCard[1] = noCardBut;
        container.add(noCardBut);

        //创建三个玩家前方的提示文字：倒计时
        //每个玩家一个
        //左边的电脑玩家是0
        //中间的自己是1
        //右边的电脑玩家是2
        for (int i = 0; i < 3; i++) {
            time[i] = new JTextField("倒计时:");
            time[i].setEditable(false);
            time[i].setVisible(false);
            container.add(time[i]);
        }
        time[0].setBounds(140, 230, 60, 20);
        time[1].setBounds(374, 360, 60, 20);
        time[2].setBounds(620, 230, 60, 20);

        //创建地主图标
        diZhu = new JLabel(new ImageIcon("src/image/dizhu.png"));
        diZhu.setVisible(false);
        diZhu.setSize(40, 40);
        container.add(diZhu);

        //也是背景 两端那个有用用哪个
        JLabel background = new JLabel(new ImageIcon("src/image/背景.jpg"));
        background.setBounds(0, 0, w, h);
        container.add(background);

    }

    //设置界面
    public void initJFrame() {
        this.setTitle("斗地主");//设置标题
        this.setSize(w, h);//设置大小
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//设置关闭模式
        this.setResizable(false);//设置窗口无法进行调节
        this.setLocationRelativeTo(null);//界面居中
        //获取界面中的隐藏容器
        //设置标题
        //获取界面中的隐藏容器，以后直接用无需再次调用方法获取了
        container = this.getContentPane();
        //取消内部默认的居中放置
        container.setLayout(null);
    }

    public void qiangdizhu() throws InterruptedException, IOException {
        switch (player.playerID) {
            case 1:
                dizhufenshu = new JButton[]{fen10, fen11, fen12, fen13};
                for (int i = 0; i < 4; i++) {
                    dizhufenshu[i].setBounds(230 + 90 * i, 350, 80, 20);
                    dizhufenshu[i].addActionListener(this);//绑定鼠标事件
                    container.add(dizhufenshu[i]);
                }
                time[0] = new JTextField("倒计时:");
                time[0].setBounds(240, 400, 60, 20);
                time[0].setVisible(true);
                container.add(time[0]);
                po1 = new PlayerOperation1(this, 30,player);
//        //开启倒计时
                po1.start();
                String e=null;
                BufferedReader in5 = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                String rubbish=in5.readLine();
                while (e == null) {
                    e = in5.readLine();
                    System.out.println(e);
                    ArrayList<String> datalist = new ArrayList<>();
                    String[] splitArray = e.split("#");
                    Collections.addAll(datalist, splitArray);
                    dizhuID = Integer.parseInt(datalist.get(1));
                }
                System.out.println(dizhuID);
                showDizhu();
                break;
            case 2:

                wait = new JTextField("等待操作中...");
                wait.setBounds(100, 100, 100, 30);
                wait.setVisible(true);
                container.add(wait);
                BufferedReader in1 = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                String a = null;
                while (a == null) {
                    a = in1.readLine();
                    System.out.println(a);
                }
                if (a.endsWith("$")) {
                    a = a.substring(0, a.length() - 1);
                }
                ArrayList<String> datalist = new ArrayList<>();
                String[] splitArray = a.split("#");
                Collections.addAll(datalist, splitArray);
                qiangdizhu2();
                String d=in1.readLine();
                while(d==null){
                    d=in1.readLine();
                }
                System.out.println(d);
                ArrayList<String> datalist1 = new ArrayList<>();
                String[] splitArray1 = d.split("#");
                Collections.addAll(datalist1, splitArray1);
                dizhuID = Integer.parseInt(datalist1.get(1));
                System.out.println(dizhuID);
                showDizhu();
                break;
            case 3:
                wait = new JTextField("等待操作中...");
                wait.setBounds(100, 100, 100, 30);
                wait.setVisible(true);
                container.add(wait);
                BufferedReader in2 = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                String b = null;
                while (b == null) {
                    b = in2.readLine();
                    System.out.println(b);
                }
                if (b.endsWith("$")) {
                    b = b.substring(0, b.length() - 1);
                }
                ArrayList<String> datalist2 = new ArrayList<>();
                String[] splitArray2 = b.split("#");
                Collections.addAll(datalist2, splitArray2);
                this.repaint();
                qiangdizhu3();
                String f=in2.readLine();
                while(f==null){
                    f=in2.readLine();
                }
                System.out.println(f);
                ArrayList<String> datalist3 = new ArrayList<>();
                String[] splitArray3 = f.split("#");
                Collections.addAll(datalist3, splitArray3);
                dizhuID = Integer.parseInt(datalist3.get(1));
                System.out.println(dizhuID);
                showDizhu();
                container.repaint();
                break;
        }
        player.isLandlord= player.playerID == dizhuID;
    }

    private void showDizhu() {
        if(player.playerID==dizhuID){
            diZhu=new JLabel();
            diZhu.setBounds(100,400,200,200);
            diZhu.setIcon(new ImageIcon("src/image/dizhu.png"));
            diZhu.setVisible(true);
            player.number+=3;
            container.add(diZhu);
            container.repaint();
        }else if((player.playerID-dizhuID+3)%3==1){
            player.numberleft+=3;
            diZhu=new JLabel();
            diZhu.setBounds(120,40,200,200);
            diZhu.setIcon(new ImageIcon("src/image/dizhu.png"));
            diZhu.setVisible(true);
            container.add(diZhu);
            container.repaint();
        }else{
            player.numberright+=3;
            diZhu=new JLabel();
            diZhu.setBounds(630,40,200,200);
            diZhu.setIcon(new ImageIcon("src/image/dizhu.png"));
            diZhu.setVisible(true);
            container.add(diZhu);
            container.repaint();
        }
        container.remove(time[0]);
        int flag=0;
        for(Poker poker : lordList){

            poker.turnFront();
            if(player.playerID==dizhuID){
                Common.move(poker, poker.getLocation(), new Point(180 + (flag+17) * 21, 450));
                player11.add(poker);
            }else if((player.playerID-dizhuID+3)%3==1){
                poker.turnRear();
                Common.move(poker, poker.getLocation(), new Point(50, 60 + (flag+17) * 15));
                player00.add(poker);
            }else{
                poker.turnRear();
                Common.move(poker, poker.getLocation(), new Point(700, 60 + (flag+17) * 15));
                player22.add(poker);
            }
            container.setComponentZOrder(poker, 0);
            for (int i = 0; i < 3; i++) {
                //排序
                Common.order(playerList.get(i));
                //重新摆放顺序
                Common.rePosition(this, playerList.get(i), i);
            }
            flag++;
        }
        Thread playgameThread = new Thread(() -> {
            try {
                i=dizhuID;
                playgame(i);
            } catch (InterruptedException | IOException e) {
                e.printStackTrace();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        });
        playgameThread.start();
    }

    private void playgame(int i) throws InterruptedException, IOException, SQLException {
        System.out.println("开始游戏！");
        for(Poker poker :player11){
            poker.setCanClick(true);
        }
        player.LastpokeGroup.isLegal();
        player.LastLastpokeGroup.isLegal();
        while (true) {
            System.out.println("当前玩家" + i);
            if (i == player.playerID) {
                if(poker11!=null){
                    for(Poker poker:poker11){
                        container.remove(poker);
                    }
                }
                container.repaint();
                buttonShow();
                flag1=true;
                while(flag1){
                }
            } else {
                if ((player.playerID - 1 - i) % 3 == 0) {
                    System.out.println("左侧玩家出牌");
                } else if ((player.playerID + 1 - i) % 3 == 0) {
                    System.out.println("右侧玩家出牌");
                }
                BufferedReader in1 = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                String b = in1.readLine();
                System.out.println(b);
                if (b.endsWith("$")) {
                    b = b.substring(0, b.length() - 1);
                }
                ArrayList<String> bdatalist = new ArrayList<>();
                String[] splitArray = b.split("#");
                Collections.addAll(bdatalist, splitArray);
                System.out.println("需播放" + bdatalist.get(2));

//                MusicPlayer.getInstance().changePlay("src/music/"+bdatalist.get(2)+".wav");

                if (bdatalist.get(0).equals("playcard")) {
                    if ((player.playerID - 1 - i) % 3 == 0) {
                        container.repaint();
                        ArrayList<String> cards = new ArrayList<>();//牌arraylist
                        Collections.addAll(cards, bdatalist.get(3).split(" "));
                        int cardnumber = cards.size();//牌的数量
                        //左侧显示
                        player.numberleft -= cardnumber;
                        System.out.println(cardnumber+"card");
                        System.out.println(player00.size()+"989");
                        Point point = new Point();
                        point.x = 220;
                        point.y = (530 / 2) - (cardnumber + 1) * 15 / 2;
                        for (int m = 0; m < cardnumber; m++) {
                            player00.get(0).setName(panduan(cards.get(m)));
                            point.y += 15;
                            Common.move(player00.get(0), player00.get(0).getLocation(), point);
                            player00.get(0).turnFront();
                            poker00.add(player00.get(0));
                            player00.remove(0);

                            container.repaint();
//                            Common.rePosition(this, player00, 1);
                        }
                    } else if ((player.playerID + 1 - i) % 3 == 0) {
                        ArrayList<String> cards = new ArrayList<>();//牌arraylist
                        Collections.addAll(cards, bdatalist.get(3).split(" "));
                        int cardnumber = cards.size();//牌的数量
                        //左侧显示
                        player.numberright -= cardnumber;
                        Point point = new Point();
                        point.x = 580;
                        point.y = (530 / 2) - (cardnumber + 1) * 15 / 2;
                        for (int m = 0; m < cardnumber; m++) {
                            player22.get(0).setName(panduan(cards.get(m)));
                            point.y += 15;
                            Common.move(player22.get(0), player22.get(0).getLocation(), point);
                            player22.get(0).turnFront();
                            poker22.add(player22.get(0));
                            player22.remove(0);

                            container.repaint();
//                            Common.rePosition(this, player22, 1);
                        }
                    }
                    player.LastLastpokeGroup.removeAll();
                    player.LastLastpokeGroup.pokegroup.addAll(player.LastpokeGroup.pokegroup);
                    player.LastLastpokeGroup.isLegal();
                    player.LastpokeGroup.removeAll();
                    player.LastpokeGroup.addPro(bdatalist.get(3));
                    player.LastpokeGroup.isLegal();
                    System.out.println("pokegroup" + player.pokeGroup.getpokegroup());
                    System.out.println("last" + player.LastpokeGroup.getpokegroup());
                    System.out.println("last" + player.LastLastpokeGroup.getpokegroup());
                    if(bdatalist.get(2).equals("不出")){
                        if((player.playerID - 1 - i) % 3 == 0){
                            buyao(1);
                            for(Poker poker:poker00){
                                container.remove(poker);
                            }
                        }
                        else if ((player.playerID + 1 - i) % 3 == 0){
                            if(f==1){
                                for(Poker poker:poker00){
                                    container.remove(poker);
                                }
                            }
                            buyao(2);
                            for(Poker poker:poker22){
                                container.remove(poker);
                            }
                        }
                    }
                    if(Objects.equals((player.LastLastpokeGroup.getpokegroup()).substring(0, 1), "不出") &&Objects.equals((player.LastpokeGroup.getpokegroup()).substring(0, 1), "不出")){
                        for(Poker poker:zancun){
                            container.remove(poker);
                        }
                        player.LastpokeGroup.removeAll();
                        player.LastLastpokeGroup.removeAll();
                    }
                    f=0;
                }
                if (bdatalist.get(0).equals("victory")) {
                    if ((player.playerID - 1 - i) % 3 == 0) {
                        ArrayList<String> cards = new ArrayList<>();//牌arraylist
                        Collections.addAll(cards, bdatalist.get(3).split(" "));
                        int cardnumber = cards.size();//牌的数量
                        //左侧显示
                        player.numberleft -= cardnumber;


                    } else if ((player.playerID + 1 - i) % 3 == 0) {
                        ArrayList<String> cards = new ArrayList<>();//牌arraylist
                        Collections.addAll(cards, bdatalist.get(3).split(" "));
                        int cardnumber = cards.size();//牌的数量
                        //右侧显示
                        player.numberright -= cardnumber;


                    }
                    if (bdatalist.get(1).equals("true")) {
                        user.setExp(user.getExp()+3);
                        Connection connection= JDBC.getConnection();
                        Statement statement=connection.createStatement();
                        String sql = "UPDATE user SET exp = '" + user.getExp()+ "' WHERE username = '" + user.getUsername() + "'";
                        statement.executeUpdate(sql);
                        showJDialog("地主获胜，抱歉您输了!");
                    } else{
                        if (player.isLandlord) {
                            user.setExp(user.getExp()+3);
                            user.setHappyDou(user.getHappyDou()-100);
                            Connection connection= JDBC.getConnection();
                            Statement statement=connection.createStatement();
                            String sql1 = "UPDATE user SET happyDou = '" + user.getHappyDou()+ "' WHERE username = '" + user.getUsername() + "'";
                            statement.executeUpdate(sql1);
                            String sql = "UPDATE user SET exp = '" + user.getExp()+ "' WHERE username = '" + user.getUsername() + "'";
                            statement.executeUpdate(sql);
                            showJDialog("农民获胜，抱歉您输了(欢乐豆-100)");
                        } else {
                            user.setExp(user.getExp()+5);
                            user.setHappyDou(user.getHappyDou()+200);
                            Connection connection= JDBC.getConnection();
                            Statement statement=connection.createStatement();
                            String sql1 = "UPDATE user SET exp = '" + user.getExp()+ "' WHERE username = '" + user.getUsername() + "'";
                            String sql2 = "UPDATE user SET happyDou = '" + user.getHappyDou()+ "' WHERE username = '" + user.getUsername() + "'";
                            statement.executeUpdate(sql1);
                            statement.executeUpdate(sql2);
                            showJDialog("农民获胜，恭喜您赢了!(欢乐豆+200)");

                        }
                    }

                    break;
                }



            }
            i++;
            if (i == 4) {
                i = i - 3;
            }
        }
    }
    private void showJDialog(String content) { //提示弹窗
        JDialog jDialog = new JDialog(); //创建一个弹框对象
        jDialog.setSize(300, 150);//给弹框设置大小
        jDialog.setAlwaysOnTop(true);//让弹框置顶
        jDialog.setLocationRelativeTo(null);//让弹框居中
        jDialog.setModal(true);//弹框不关闭永远无法操作下面的界面

        //创建JLabel对象管理文字并添加到弹框当中
        JLabel warning = new JLabel(content);
        warning.setBounds(0, 0, 180, 90);
        jDialog.getContentPane().add(warning);
        //展示弹框
        jDialog.setVisible(true);
    }
    private void buyao(int i) {
        if(i==1){
            JTextField buyao=new JTextField("不要");
            buyao.setBounds(220,300,60,20);
            buyao.setVisible(true);
            container.add(buyao);
        }
        else if(i==2){
            JTextField buyao=new JTextField("不要");
            buyao.setBounds(580,300,60,20);
            buyao.setVisible(true);
            container.add(buyao);
        }
        container.repaint();
    }

    private void buttonShow() {
        yao=new JButton("出牌");
        yao.setBounds(320, 400, 60, 20);
        yao.addActionListener(this);
        yao.setVisible(true);
        container.add(yao);

        NoYao=new JButton("不出");
        NoYao.setBounds(420, 400, 60, 20);
        NoYao.addActionListener(this);
        NoYao.setVisible(true);
        container.add(NoYao);
        container.repaint();
    }
    private void buttonHidden(){
        yao.setVisible(false);
        NoYao.setVisible(false);
        container.repaint();
    }

    private void qiangdizhu2() {
        SwingUtilities.invokeLater(() -> {
            switch (player.playerID) {
                case 2:
                    dizhufenshu = new JButton[]{fen10, fen11, fen12, fen13};
                    for (int i = 0; i < 4; i++) {
                        dizhufenshu[i].setBounds(230 + 90 * i, 350, 80, 20);
                        dizhufenshu[i].addActionListener(this); // 绑定鼠标事件
                        container.add(dizhufenshu[i]);
                    }
                    time[0] = new JTextField("倒计时:");
                    time[0].setBounds(240, 400, 60, 20);
                    time[0].setVisible(true);
                    container.add(time[0]);
                    po1 = new PlayerOperation1(this, 30,player);
                    // 开启倒计时
                    po1.start();
                    container.validate();
                    container.repaint();
                    break;
                case 3:
                    wait.setBounds(100, 100, 100, 30);
                    break;
                case 1:
                    wait.setBounds(300, 100, 100, 30);
                    break;
            }
        });
    }

    private void qiangdizhu3() {
        SwingUtilities.invokeLater(() -> {
            switch (player.playerID) {
                case 3:
                    dizhufenshu = new JButton[]{fen10, fen11, fen12, fen13};
                    for (int i = 0; i < 4; i++) {
                        dizhufenshu[i].setBounds(230 + 90 * i, 350, 80, 20);
                        dizhufenshu[i].addActionListener(this); // 绑定鼠标事件
                        container.add(dizhufenshu[i]);
                    }
                    time[0] = new JTextField("倒计时:");
                    time[0].setBounds(240, 400, 60, 20);
                    time[0].setVisible(true);
                    container.add(time[0]);
                    po1 = new PlayerOperation1(this, 30,player);
                    // 开启倒计时
                    po1.start();
                    container.validate();
                    container.repaint();
                    break;
                case 1:
                    wait.setBounds(100, 100, 100, 30);
                    break;
                case 2:
                    wait.setBounds(300, 100, 100, 30);
                    break;
            }
        });
    }

    public String fanpanduan(String a) {
        switch(a.charAt(0)){
            case '5':
                if(a.charAt(2)=='1') return "_小王";
                else return "_大王";
            case '4':
                if(a.charAt(2)=='1'&&a.length()==3){
                    return "♦"+"A";
                }else if(a.charAt(2)=='1'&&a.charAt(3)=='1'){
                    return "♦"+"J";
                }else if(a.charAt(2)=='1'&&a.charAt(3)=='2'){
                    return "♦"+"Q";
                }else if(a.charAt(2)=='1'&&a.charAt(3)=='3'){
                    return "♦"+"K";
                }else{
                    return "♦"+a.substring(2);
                }

            case '3':
                if(a.charAt(2)=='1'&&a.length()==3){
                    return "♣"+"A";
                }else if(a.charAt(2)=='1'&&a.charAt(3)=='1'){
                    return "♣"+"J";
                }else if(a.charAt(2)=='1'&&a.charAt(3)=='2'){
                    return "♣"+"Q";
                }else if(a.charAt(2)=='1'&&a.charAt(3)=='3'){
                    return "♣"+"K";
                }else {
                    return "♣" + a.substring(2);
                }
            case '2':
                if(a.charAt(2)=='1'&&a.length()==3){
                    return "♥"+"A";
                }else if(a.charAt(2)=='1'&&a.charAt(3)=='1'){
                    return "♥"+"J";
                }else if(a.charAt(2)=='1'&&a.charAt(3)=='2'){
                    return "♥"+"Q";
                }else if(a.charAt(2)=='1'&&a.charAt(3)=='3'){
                    return "♥"+"K";
                }else {
                    return "♥" + a.substring(2);
                }
            case '1':
                if(a.charAt(2)=='1'&&a.length()==3){
                    return "♠"+"A";
                }else if(a.charAt(2)=='1'&&a.charAt(3)=='1'){
                    return "♠"+"J";
                }else if(a.charAt(2)=='1'&&a.charAt(3)=='2'){
                    return "♠"+"Q";
                }else if(a.charAt(2)=='1'&&a.charAt(3)=='3'){
                    return "♠"+"K";
                }else {
                    return "♠" + a.substring(2);
                }
        }
        return null;
    }
    public String panduan(String a) {
        if (Objects.equals(a, "_小王")) {
            return 5 + "-" + 1;
        } else if (Objects.equals(a, "_大王")) {
            return 5 + "-" + 2;
        } else if (Objects.equals(a.substring(0, 1), "♦")) {
            switch (a.substring(1)) {
                case "A":
                    return 4 + "-" + 1;
                case "J":
                    return 4 + "-" + 11;
                case "Q":
                    return 4 + "-" + 12;
                case "K":
                    return 4 + "-" + 13;
                default:
                    return 4 + "-" + a.substring(1);
            }

        } else if (Objects.equals(a.substring(0, 1), "♥")) {
            switch (a.substring(1)) {
                case "A":
                    return 2 + "-" + 1;
                case "J":
                    return 2 + "-" + 11;
                case "Q":
                    return 2 + "-" + 12;
                case "K":
                    return 2 + "-" + 13;
                default:
                    return 2 + "-" + a.substring(1);
            }
        } else if (Objects.equals(a.substring(0, 1), "♣")) {
            switch (a.substring(1)) {
                case "A":
                    return 3 + "-" + 1;
                case "J":
                    return 3 + "-" + 11;
                case "Q":
                    return 3 + "-" + 12;
                case "K":
                    return 3 + "-" + 13;
                default:
                    return 3 + "-" + a.substring(1);
            }
        } else {
            switch (a.substring(1)) {
                case "A":
                    return 1 + "-" + 1;
                case "J":
                    return 1 + "-" + 11;
                case "Q":
                    return 1 + "-" + 12;
                case "K":
                    return 1 + "-" + 13;
                default:
                    return 1 + "-" + a.substring(1);
            }
        }

    }

    private void animateShuffling() {
        for (int i = 1; i <= 5; i++) {
            for (int j = 1; j <= 13; j++) {
                if ((i == 5) && (j > 2)) {
                    break;
                } else {
                    Poker poker = new Poker(this, i + "-" + j, false);
                    poker.setLocation(350, 150);
                    pokerList.add(poker);
                    container.add(poker);
                    container.setComponentZOrder(poker, 0);
                }
            }
        }


        //洗牌
        Collections.shuffle(pokerList);
        for (int i = 0; i < 3; i++) {
            ArrayList<Poker> list = new ArrayList<>();
            //添加到大集合中方便管理
            currentList.add(list);
        }

        for (int i = 0; i < pokerList.size(); i++) {
            //获取当前遍历的牌
            Poker poker = pokerList.get(i);

            //发三张底牌
            if (i <= 2) {
                poker.setName(panduan(lord.get(i)));
                //移动牌
                Common.move(poker, poker.getLocation(), new Point(270 + (75 * i), 10));
                //把底牌添加到集合中
                lordList.add(poker);
                continue;
            }
            //给三个玩家发牌
            if (i < 20) {
                poker.setName(panduan(player.handCards.get(i - 3)));
                //给左边的电脑发牌
                Common.move(poker, poker.getLocation(), new Point(50, 60 + (i - 3) * 15));
                player00.add(poker);
            } else if (i < 37) {
                //给中间的自己发牌
                poker.setName(panduan(player.handCards.get(i - 20)));
                Common.move(poker, poker.getLocation(), new Point(180 + (i - 20) * 21, 450));
                //把自己的牌展示正面
                poker.turnFront();
                player11.add(poker);
            } else {
                //给右边的电脑发牌
                poker.setName(panduan(player.handCards.get(i - 37)));
                Common.move(poker, poker.getLocation(), new Point(700, 60 + (i - 37) * 15));
                player22.add(poker);
            }
            //把三个装着牌的小集合放到大集合中方便管理
            playerList.add(player00);
            playerList.add(player11);
            playerList.add(player22);
            //           把当前的牌至于最顶端，这样就会有牌依次错开且叠起来的效果
            container.setComponentZOrder(poker, 0);


        }
    }
}